<template>
  <div>
    <Modal v-model="showRelatedAssetModal" :title="action.title + '关联'" :footer-hide="true" :mask-closable="false" :closable="false">
      <el-row>
        <el-col :span="24" class="head-font">{{ action.title }}关联应用信息如下：</el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="8" align="right" class="content-font">Service名称</el-col>
        <el-col :span="16" class="content-font">{{ serviceInfo.name }}</el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="8" align="right" class="content-font">Service描述</el-col>
        <el-col :span="16" class="content-font">{{ serviceInfo.description }}</el-col>
      </el-row>

      <el-row>
        <el-col :span="24" class="head-font">{{ action.title }}关联服务器如下：</el-col>
      </el-row>

      <el-row v-if="action.type === 'add'" :gutter="10">
        <el-col :span="8" align="right" class="content-font">服务器列表</el-col>
        <el-col :span="16" class="content-font">
          <el-select
            v-model="selectedChangeAssetIds"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            size="mini"
            :multiple="true"
            :remote-method="remoteMethod"
            :loading="loading"
            style="width: 260px"
          >
            <el-option v-for="item in changeAssetOptions" :key="item.id" :label="item.hostname + '(' + item.businessIp + ')'" :value="item.id">
              <span style="float: left; font-size: 12px">{{ item.businessIp }}</span>
              <span style="float: right; color: #8492a6; font-size: 12px; padding-left: 20px">
                {{ item.hostname }}
                <el-divider direction="vertical"></el-divider>
                <span style="color: #ff9900">{{ item.env }}</span>
                <el-divider direction="vertical"></el-divider>
                <span style="color: #ff9900">{{ item.zone }}</span>
              </span>
            </el-option>
          </el-select>
        </el-col>
      </el-row>

      <el-row v-if="action.type === 'remove'" :gutter="10">
        <el-col :span="8" align="right" class="content-font">解除服务器ID</el-col>
        <el-col :span="16" class="content-font">
          <el-input v-model="relatedAssetDetail.id" disabled size="mini" style="width: 260px" />
        </el-col>
        <el-col :span="8" align="right" class="content-font">解除服务器IP</el-col>
        <el-col :span="16" class="content-font">
          <el-input v-model="relatedAssetDetail.businessIp" disabled size="mini" style="width: 260px" />
        </el-col>
        <el-col :span="8" align="right" class="content-font">解除服务器主机名</el-col>
        <el-col :span="16" class="content-font">
          <el-input v-model="relatedAssetDetail.hostname" disabled size="mini" style="width: 260px" />
        </el-col>
      </el-row>

      <el-row style="margin-top: 20px">
        <el-col :span="24" align="right">
          <el-button type="primary" size="small" @click="ok">确认</el-button>
          <el-button size="small" @click="cancel">取消</el-button>
        </el-col>
      </el-row>
    </Modal>
  </div>
</template>

<script>
import { getCmdbAssetListByPage, getCmdbAsset } from '@/api/cmdb/asset'
import { bulkAddServiceAsset, bulkDeleteServiceAsset } from '@/api/cmdb/service'
import { errorNotify } from '@/libs/util'
import checkPermission from '@/utils/permission'
import { snakeCaseObject } from '@/libs/object'

export default {
  name: 'RelatedAsset',
  props: {
    showRelatedAssetModal: {
      type: Boolean,
      default: false,
      require: true
    },
    serviceInfo: {
      type: Object,
      default() {
        return {
          id: '',
          name: ''
        }
      }
    },
    action: {
      type: Object,
      default() {
        return {
          source: 'detail',
          title: '添加',
          type: 'add'
        }
      }
    },
    changeAssetIds: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      selectedChangeAssetIds: this.$lodash.cloneDeep(this.changeAssetIds),
      changeAssetOptions: [],
      relatedAssetDetail: {},
      loading: false,
      relatedAssetDetailOptions: {},
      submitAssetIds: []
    }
  },
  computed: {},
  watch: {
    selectedChangeAssetId(val, oldVal) {
      this.relatedAssetDetail = this.relatedAssetDetailOptions[val]
    }
  },
  mounted() {
    this.setInitModalData()
  },
  methods: {
    checkPermission,
    setInitModalData() {
      if (this.selectedChangeAssetId !== [] && this.action.type === 'remove') {
        this.getCmdbAsset()
      } else {
        this.getCmdbAssetListByPage()
      }
    },
    ok() {
      if (this.selectedChangeAssetId !== [] && this.action.type === 'remove') {
        this.bulkDeleteServiceAsset()
      } else if (this.selectedChangeAssetId !== [] && this.action.type === 'add') {
        this.bulkAddServiceAsset()
      } else {
        this.$message({
          message: '请校验参数是否正确填写',
          type: 'warning'
        })
      }
    },
    cancel() {
      this.show = false
      this.$emit('on-asset-change', { type: 'cancel', status: false })
    },
    async bulkAddServiceAsset() {
      try {
        const { data } = await bulkAddServiceAsset(this.serviceInfo.id, snakeCaseObject({ asset_ids: this.selectedChangeAssetIds }))
        this.$emit('on-asset-change', { type: this.action.type, status: false, serviceInfo: data })
      } catch (e) {
        errorNotify(e)
      }
    },
    async bulkDeleteServiceAsset() {
      try {
        console.log(this.selectedChangeAssetIds)
        const { data } = await bulkDeleteServiceAsset(this.serviceInfo.id, snakeCaseObject({ asset_ids: this.selectedChangeAssetIds }))
        this.$emit('on-asset-change', { type: this.action.type, status: false, serviceInfo: data })
      } catch (e) {
        errorNotify(e)
      }
    },
    async getCmdbAsset() {
      try {
        console.log(this.changeAssetIds)
        const { data } = await getCmdbAsset(this.changeAssetIds[0])
        this.relatedAssetDetail = data
      } catch (e) {
        errorNotify(e)
      }
    },
    async getCmdbAssetListByPage(query) {
      try {
        const params = {
          page_size: 30,
          search: query
        }
        const { data } = await getCmdbAssetListByPage(params)
        const tempDataArray = []
        data.data.forEach((item, index) => {
          if (this.serviceInfo.assets.map((item) => item.id).indexOf(item.id) === -1) {
            tempDataArray.push({
              id: item.id,
              hostname: item.hostname,
              businessIp: item.businessIp,
              env: item.env,
              zone: item.zone
            })
          }
        })
        this.changeAssetOptions = tempDataArray
        console.log(this.changeAssetOptions)
        // const tempDataDict = {}
        // data.data.forEach((item, index) => {
        //   tempDataDict[item.id] = item
        // })
        // this.relatedAssetDetailOptions = tempDataDict
      } catch (e) {
        errorNotify(e)
      } finally {
        this.loading = false
      }
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.getCmdbAssetListByPage(query)
        }, 200)
      } else {
        this.changeAssetOptions = []
      }
    }
  }
}
</script>

<style scoped>
.head-font {
  color: #515a6e;
  line-height: 32px;
  font-size: 14px;
}
.content-font {
  color: #515a6e;
  line-height: 32px;
  font-size: 12px;
}
</style>
